package com.luobr.backend.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luobr.backend.annotation.AuthCheck;
import com.luobr.backend.common.BaseResponse;
import com.luobr.backend.common.ResponseCode;
import com.luobr.backend.common.ResultUtils;
import com.luobr.backend.constant.UserConstant;
import com.luobr.backend.exception.BusinessException;
import com.luobr.backend.exception.ThrowUtils;
import com.luobr.backend.manage.auth.SpaceUserAuthManager;
import com.luobr.backend.model.dto.space.*;
import com.luobr.backend.model.dto.space.SpaceEditRequest;
import com.luobr.backend.model.dto.space.SpaceUpdateRequest;
import com.luobr.backend.model.entity.Space;
import com.luobr.backend.model.entity.User;
import com.luobr.backend.model.enums.SpaceLevelEnum;
import com.luobr.backend.model.vo.space.SpaceLevel;
import com.luobr.backend.model.vo.space.SpaceVO;
import com.luobr.backend.model.vo.user.UserLoginVO;
import com.luobr.backend.service.SpaceService;
import com.luobr.backend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 罗念笙
 * @date 2025/3/11 17:09
 */
@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SpaceService spaceService;
    @Resource
    private UserService userService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 新增空间
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,  HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(spaceAddRequest), ResponseCode.PARAMS_ERROR);
        // 获取用户信息
        UserLoginVO loginUser = userService.getLoginUser(request);
        return ResultUtils.success(spaceService.addSpace(spaceAddRequest, loginUser));
    }

    /**
     * 删除空间
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(long id, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ResponseCode.PARAMS_ERROR);
        // 获取空间和用户信息
        UserLoginVO loginUser = userService.getLoginUser(request);
        Space space = spaceService.getById(id);
        // 仅限本人和管理员可以删除空间
        ThrowUtils.throwIf(space == null, ResponseCode.PARAMS_ERROR);
        ThrowUtils.throwIf(!UserConstant.USER_ROLE.ADMIN.equals(loginUser.getUserRole()) &&
                !space.getUserId().equals(loginUser.getId()), ResponseCode.NO_AUTH_ERROR);
        // 删除空间
        boolean result = spaceService.removeById(id);
        ThrowUtils.throwIf(!result, new BusinessException(ResponseCode.OPERATION_ERROR));
        return ResultUtils.success(true);
    }

    /**
     * 编辑空间（仅限本人管理员权限）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(spaceEditRequest) || spaceEditRequest.getId() <= 0, ResponseCode.PARAMS_ERROR);
        // 转换成空间实体
        Space space = SpaceEditRequest.dtoToObj(spaceEditRequest);
        // 校验空间信息
        spaceService.validSpace(space);
        // 校验原空间是否存在
        Space oldSpace = spaceService.getById(space.getId());
        ThrowUtils.throwIf(ObjUtil.isNull(oldSpace), ResponseCode.OPERATION_ERROR, "更新空间失败！");
        // 仅限本人和管理员可以编辑空间
        UserLoginVO loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(!UserConstant.USER_ROLE.ADMIN.equals(loginUser.getUserRole()) &&
                !space.getUserId().equals(loginUser.getId()), ResponseCode.NO_AUTH_ERROR);
        // 编辑空间
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ResponseCode.OPERATION_ERROR, "更新空间失败！");
        return ResultUtils.success(true);
    }

    /**
     * 更新空间（仅限管理员权限）
     */
    @PostMapping("/update")
    @AuthCheck(roleValue = UserConstant.USER_ROLE.ADMIN)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        ThrowUtils.throwIf(ObjUtil.isNull(spaceUpdateRequest) || spaceUpdateRequest.getId() <= 0,ResponseCode.PARAMS_ERROR);
        // 将实体类和 DTO 进行转换
        Space space = SpaceUpdateRequest.dtoToObj(spaceUpdateRequest);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ResponseCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 通过空间 id 获取脱敏后的空间信息
     */
    @PostMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ResponseCode.PARAMS_ERROR);
        // 获取审核通过的空间和用户信息
        Space space = spaceService.getOne(new QueryWrapper<Space>().eq("id", id));
        ThrowUtils.throwIf(ObjUtil.isNull(space), ResponseCode.PARAMS_ERROR);
        User user = userService.getOne(new QueryWrapper<User>().eq("id", space.getUserId()));
        // 添加权限列表
        SpaceVO spaceVO = SpaceVO.objToVo(space, UserLoginVO.objToLoginVo(user));
        UserLoginVO loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 空间信息添加用户信息
        return ResultUtils.success(spaceVO);
    }

    /**
     * 通过空间 id 获取脱敏后的空间信息
     */
    @PostMapping("/get")
    @AuthCheck(roleValue = UserConstant.USER_ROLE.ADMIN)
    public BaseResponse<Space> getSpaceById(long id) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ResponseCode.PARAMS_ERROR);
        // 获取空间和用户信息
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ResponseCode.PARAMS_ERROR);
        // 空间信息添加用户信息
        return ResultUtils.success(space);
    }

    /**
     * 获取脱敏后的空间信息分页数据
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(spaceQueryRequest), ResponseCode.PARAMS_ERROR);
        // 获取分页条件
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        // 获取到分页数据
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize), spaceService.getQueryWrapper(spaceQueryRequest));
        // 返回分页数据
        return ResultUtils.success(spacePage);
    }

    /**
     * 获取空间等级列表
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}